package com.da.lon.wang.xlg.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.Toast;

import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.ResultBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListenerReplay;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.WebViewUtil;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.view.MovieRecorderView;
import com.da.lon.wang.xlg.view.MovieRecorderView.OnRecordFinishListener;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

public class VideoActivity extends Activity {

    private MovieRecorderView mRecorderView;// 视频录制控件
    private Button mShootBtn;// 视频开始录制按钮
    private boolean isFinish = true;
    private boolean success = false;// 防止录制完成后出现多次跳转事件
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (success) {
                finishActivity();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ouka_video);
        mRecorderView = (MovieRecorderView) findViewById(R.id.movieRecorderView);
        mShootBtn = (Button) findViewById(R.id.shoot_button);

        // 用户长按事件监听
        mShootBtn.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {// 用户按下拍摄按钮
                    mShootBtn.setBackgroundResource(R.drawable.bg_movie_add_shoot_select);
                    mRecorderView.record(new OnRecordFinishListener() {

                        @Override
                        public void onRecordFinish() {
                            if (!success && mRecorderView.getTimeCount() < 10) {// 判断用户按下时间是否大于10秒
                                success = true;
                                handler.sendEmptyMessage(1);
                            }
                        }
                    });
                } else if (event.getAction() == MotionEvent.ACTION_UP) {// 用户抬起拍摄按钮
                    mShootBtn.setBackgroundResource(R.drawable.bg_movie_add_shoot);
                    if (mRecorderView.getTimeCount() > 3) {// 判断用户按下时间是否大于3秒
                        if (!success) {
                            success = true;
                            handler.sendEmptyMessage(1);
                        }
                    } else {
                        success = false;
                        if (mRecorderView.getmVecordFile() != null)
                            mRecorderView.getmVecordFile().delete();// 删除录制的过短视频
                        mRecorderView.stop();// 停止录制
                        Toast.makeText(VideoActivity.this, "视频录制时间太短", Toast.LENGTH_SHORT).show();
                    }
                }
                return true;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        isFinish = true;
        if (mRecorderView.getmVecordFile() != null)
            mRecorderView.getmVecordFile().delete();// 视频使用后删除
        MobclickAgent.onResume(this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        isFinish = false;
        success = false;
        mRecorderView.stop();// 停止录制
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    // 视频录制结束后，跳转的函数
    private void finishActivity() {
        if (isFinish) {
            mRecorderView.stop();

            String url = "http://okapi.hhecz.com/Ok-orderdelivery";
            HttpLoader<ResultBean> httpLoader = new HttpLoader<ResultBean>(this, url, ResultBean.class);
            AjaxParams params = new AjaxParams();
            try {
                // List<ImageInfo> imageInfos =
                // MyApplication.getInstance().imageInfos;
                // for (int i = 0; i < imageInfos.size(); i++) {
                params.put("file0", mRecorderView.getmVecordFile());
                // }
                if (WebViewUtil.pictureOrderInfo != null) {
                    params.put("ordersid", WebViewUtil.pictureOrderInfo.getOrdersid());
                    // params.put("limitcount",
                    // WebViewUtil.pictureOrderInfo.limitcount);
                }
                params.put("id", PreferenceUtils.getInstance().getSettingStr(PreferencesConfig.USER_ID, ""));
                params.put("user_key", PreferenceUtils.getInstance().getSettingStr(PreferencesConfig.USER_KEY, ""));
                params.put("token", XLGDataUtils.encrypt2MD5("Ok" + XLGConstants.SECRET + "orderdelivery"));
                params.put("device_type", "1");


                httpLoader.setReplayManagerListener(new OnWebLoadListenerReplay<ResultBean>() {

                    @Override
                    public void OnStart() {
                        // showDialog("上传中");
                    }

                    @Override
                    public void OnError(String error) {
                        // dismissDialog();
                        Toast.makeText(VideoActivity.this, "上传失败", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onSuccess(ResultBean t, String result) {
                        // dismissDialog();
                        if (t != null) {
                            if (t.getCode().equals("000000")) {
                                Toast.makeText(VideoActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(XLGConstants.REPLAY_SUCCESS);
                                intent.putExtra("content", result);
                                intent.putExtra("type", "order_picture");
                                sendBroadcast(intent);
                                finish();
                            } else {
                                Toast.makeText(VideoActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }

                    }
                });

                httpLoader.loadReplayData(params);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        success = false;
    }

    /**
     * 录制完成回调
     */
    public interface OnShootCompletionListener {
        public void OnShootSuccess(String path, int second);

        public void OnShootFailure();
    }
}
